﻿#region File Header
/***********************************************************************
 * Copyright © 2013 Beals Software
 * All Rights Reserved
************************************************************************
Author: Donald Beals
Date: February 4th, 2013
Description: TODO: Write a description of this file here.
****************************** Change Log ******************************
02.04.13 - Created initial file. (dbeals)
***********************************************************************/
#endregion

#region Using Statements
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
#endregion

namespace GameJolt.Async
{
	/// <summary>
	/// 
	/// </summary>
	internal static class AsyncHelper
	{
		public static AsyncResult<TResult> BeginAsyncCall<TResult>(Func<AsyncResult<TResult>, TResult> method, AsyncCallback callback, object asyncState, object coreData)
		{
			var outputAsyncResult = new AsyncResult<TResult>(callback, asyncState, coreData);
			System.Threading.ThreadPool.QueueUserWorkItem((data) =>
			{
				var asyncResult = (AsyncResult<TResult>)data;
				try
				{
					var outputValue = method(asyncResult);
					asyncResult.SetAsCompleted(outputValue, false);
				}
				catch(Exception exception)
				{
					asyncResult.SetAsCompleted(exception, false);
				}
			}, outputAsyncResult);
			return outputAsyncResult;
		}

		public static TResult EndAsyncCall<TResult>(IAsyncResult result)
		{
			var tempResult = (AsyncResult<TResult>)result;
			return tempResult.EndInvoke();
		}
	}
}
